package com.toptech.downloadmanager.download;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.LinearGradient;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.ProgressBar;

import com.toptech.downloadmanager.FileInfo;
import com.toptech.downloadmanager.RemoteService;
import com.toptech.downloadmanager.TaskInfo;
import com.toptech.downloadmanager.ToolUtils.ContantsUtils;
import com.toptech.downloadmanager.ToolUtils.LitePalUtils;
import com.toptech.downloadmanager.ToolUtils.lg;
import com.toptech.downloadmanager.db.DBThreadListener;
import com.toptech.downloadmanager.db.DBThreadListenerImp;
import com.toptech.downloadmanager.entity.ThreadInfo;

import org.litepal.crud.DataSupport;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by zhengshaorui on 2017/3/1.
 */

public class DownloadTaskManger {
    private static final String TAG = "zsr";
    private static Context mContext;

    public static int TaskCount;

    private static int LastTaskCount ;


    //正在下载的任务
    private List<FileInfo> mFileInfoLoadings = new ArrayList<FileInfo>();
    //等待的任务
    private List<FileInfo> mFileInfoWaitings = new ArrayList<FileInfo>();
    //总任务
    private List<FileInfo> mFileInfos = new ArrayList<FileInfo>();

    private ProgressBar mProgressBar;

    private DBThreadListener mDbThreadListener;

    public static int getTaskCount() {
        return TaskCount;
    }

    public static void setTaskCount(int taskCount) {


    }

    public static class Holder{
        private static DownloadTaskManger sDownloadTaskManger = new DownloadTaskManger();
        public static DownloadTaskManger getInstance(){
            return  sDownloadTaskManger;
        }
    }

    public void init(Context context){
        mContext = context;
        mDbThreadListener = new DBThreadListenerImp(mContext);
        TaskCount = RemoteService.TASKCOUNT;
        LastTaskCount = TaskCount;
        Intent intent = new Intent(mContext,DownloadService.class);
        mContext.bindService(intent,conn,Context.BIND_AUTO_CREATE);

    }






    public void completedAndStartDownload(List<FileInfo> fileInfosList){

        Log.d(TAG, "count: "+DataSupport.count(TaskInfo.class));

        //清空以前的数据
        mFileInfoLoadings.clear();
        //清空以前的数据
        mFileInfoWaitings.clear();

      /* for (FileInfo fileinfo:fileInfosList) Log.d(TAG, "getFileName: "+fileinfo.getFileName()+" "+
       fileinfo.getProgress()+" "+fileinfo.getPriority());*/

       for (FileInfo fileInfo : fileInfosList){

            if (fileInfo.getPriority() == ContantsUtils.PRIORITY_HIGHTEST){ //检查到最高级
                if (fileInfo.getProgress() < 100) {   //且进度不是小于100
                    TaskCount = 1; //把并行任务数设置为1；
                    /*fileInfo.setBtnstatus(ContantsUtils.START);
                    Intent intent = new Intent(mContext, DownloadService.class);
                    intent.putExtra("fileinfo", fileInfo);
                    mContext.startService(intent);*/
                    if (mBinder != null){
                        mBinder.startDownload(fileInfo);
                    }
                    return;//不执行下面的任务
                }
            }
       }

        for (int i = 0; i < fileInfosList.size(); i++) {
            FileInfo fileInfo = fileInfosList.get(i);
            fileInfo.setFileDir(getFileDir());  //这里重新把路径给它

            boolean istaskexsits = LitePalUtils.isTaskInfoExsits(fileInfo.getApkurl());
          //  Log.d(TAG, "completedAndStartDownload: "+fileInfo.getFileName()+istaskexsits+TaskCount);

            if (!istaskexsits) { //如果这个任务，数据库中并不存在
                TaskInfo taskInfo = new TaskInfo(0,fileInfo.getFileName(),fileInfo.getApkurl(),
                        fileInfo.getProgress(),fileInfo.getFiledownsize(),fileInfo.getFilesize(),
                        fileInfo.getThreadCount(),fileInfo.getPriority());
                taskInfo.saveThrows();//保存任务的信息到数据库

            } else{  //如果这个任务数据库已经保存了它的信息
                int progress = LitePalUtils.getTaskProgress(fileInfo.getApkurl());
               // Log.d(TAG, "completedAndStartDownload: "+progress);
                if (progress == 100)
                    continue; //且进度为100，则不添加到下载任务中
            }

            if (mFileInfoLoadings.size() < TaskCount){
                mFileInfoLoadings.add(fileInfo);
            }else{
                mFileInfoWaitings.add(fileInfo);
            }

        }

        startLoading();

    }



    public List<FileInfo> pauseAllLoadingTask(){

            /*fileInfo.setBtnstatus(ContantsUtils.PAUSE);
            Intent intent = new Intent(mContext,DownloadService.class);
            intent.putExtra("fileinfo",fileInfo);
            mContext.startService(intent);*/
            if (mBinder != null){
                mBinder.pauseAllDownload(mFileInfoLoadings);
            }

        return  mFileInfoLoadings;
    }

    public List<FileInfo> startAllLoadingTask(){
        /*for (FileInfo fileInfo : mFileInfoLoadings){
            fileInfo.setBtnstatus(ContantsUtils.START);
            Intent intent = new Intent(mContext,DownloadService.class);
            intent.putExtra("fileinfo",fileInfo);
            mContext.startService(intent);
        }*/
        if (mBinder != null){
            mBinder.startAllDownload(mFileInfoLoadings);
        }
        return  mFileInfoLoadings;
    }


    private void startLoading(){

        Log.d(TAG, "startLoading: "+mFileInfoLoadings.size());
        /*for (FileInfo fileInfo : mFileInfoLoadings){
            Intent intent = new Intent(mContext,DownloadService.class);
            intent.putExtra("fileinfo",fileInfo);
            mContext.startService(intent);
        }*/
        lg.d("mbinder: "+mBinder);
        if (!mFileInfoLoadings.isEmpty()){
            if (mBinder != null){
                mBinder.startAllDownload(mFileInfoLoadings);
            }
        }
     }



    private DownloadService.DownloadServiceBinder mBinder;
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBinder = (DownloadService.DownloadServiceBinder) service;
            lg.d("manager onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBinder = null;
            lg.d("manager onServiceDisconnected");
        }
    };

    public void pauseDownload(String url){
        if (mBinder != null){
            mBinder.pauseDownload(url);
        }
    }
    public void startDownload(FileInfo fileInfo){
        if (mBinder != null){
            mBinder.startDownload(fileInfo);
        }

    }



     /**
     * 获取文件的路径
     * @return
     */
    private String getFileDir(){
        String dir = null;
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED){
            dir = mContext.getExternalCacheDir()+"/mydownload/";
        }else {
            dir = mContext.getCacheDir()+"/mydownload/";
        }
        return dir;
    }

    /**
     * 下载回调函数
     */
    public  DownloadCallback mDownloadCallback = new DownloadCallback() {
        @Override
        public void success(FileInfo fileInfo) {

            fileInfo.setProgress(100);
            mFileinfoSuccess = fileInfo;

            Intent intent = new Intent(ContantsUtils.DOWNLOADSUCCESS);
            intent.putExtra("fileinfo",fileInfo);
            mContext.sendBroadcast(intent);
           // sendSuccessResponse(fileInfo);


            if (fileInfo.getPriority() == ContantsUtils.PRIORITY_HIGHTEST){
                TaskCount = LastTaskCount; //恢复以前默认的并行任务数
                for (int i = 0; i < RemoteService.sFileInfoList.size(); i++) {
                    FileInfo info = RemoteService.sFileInfoList.get(i);
                    if (fileInfo.getApkurl().equals(info.getApkurl())){
                        RemoteService.sFileInfoList.set(i,fileInfo);  //修改信息
                    }
                }
                completedAndStartDownload(RemoteService.sFileInfoList);
                return;
            }

            Log.d(TAG, "success: "+fileInfo.getFileName());
            for (int i = 0; i < mFileInfoLoadings.size(); i++) {
                FileInfo info = mFileInfoLoadings.get(i);
                info.setBtnstatus(ContantsUtils.HASBEENSTART);
                mFileInfoLoadings.set(i,info); //刷新task的状态

                if (fileInfo.getApkurl().equals(mFileInfoLoadings.get(i).getApkurl())){
                    mFileInfoLoadings.remove(i);
                }
            }
            if (mFileInfoLoadings.size() >= 0  && mFileInfoLoadings.size() < TaskCount) {
                if (mFileInfoWaitings.size() > 0) {
                    mFileInfoLoadings.add(mFileInfoWaitings.get(0));
                    mFileInfoWaitings.remove(0);
                }
            }

            startLoading();
            if (mFileInfoLoadings.size() == 0){
                Intent allFinish = new Intent(ContantsUtils.DOWNLOADALLFINISH);
                mContext.sendBroadcast(allFinish);
            }


        }

        @Override
        public void failed(int errorCode,final String errorMsg, final FileInfo fileInfo) {

            Intent intent = new Intent(ContantsUtils.DOWNLOADERROR);
            intent.putExtra("fileinfo",fileInfo);
            intent.putExtra("errorMsg",errorMsg);
            intent.putExtra("errorCode",errorCode);
            mContext.sendBroadcast(intent);

           // mFileinfoFail = fileInfo;
          //  sendFailResponse(errorCode,errorMsg,fileInfo);
        }

        @Override
        public void downloadStatus(String fileUrl, int status) {
            //Log.d(TAG, "downloadStatus: " + status);
        }

        @Override
        public void getDownloadInfo(FileInfo fileInfo) {
           // mFileinfoStatus = fileInfo;
            sendLoadingResponse(fileInfo);
        }
    };

    /**
     * 回调正在下载的任务到客户端
     * @param fileinfo
     */
    private void sendLoadingResponse(FileInfo fileinfo) {
        try {
            // 以广播的方式进行客户端回调
            int len = RemoteService.sCallback.beginBroadcast();
            for (int i = 0; i < len; i++) {
                try {
                    RemoteService.sCallback.getBroadcastItem(i).getLoadingTaskInfo(fileinfo); //这里的download为IServiceCallBack的方法
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                RemoteService.sCallback.finishBroadcast();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    private volatile FileInfo mFileinfoStatus;
    private volatile FileInfo mFileinfoSuccess;
    private volatile FileInfo mFileinfoFail;

    public FileInfo getFileinfoStatus(){
        return mFileinfoStatus;
    }
    public FileInfo getFileinfoSuccess(){
        return mFileinfoSuccess;
    }
    public FileInfo getFileinfoFail(){
        return mFileinfoFail;
    }

    /**删除一个任务，删除数据库
     *
     *
     * @param fileInfo
     */
    public void deleteTask(final FileInfo fileInfo){
        boolean isExsit = LitePalUtils.isTaskInfoExsits(fileInfo.getApkurl());
        //第一步，删除任务数据库
        if (isExsit){
            DataSupport.deleteAll(TaskInfo.class,"fileurl = ?",fileInfo.getApkurl());
        }
        //第二步，暂停正在下载的任务，和删除线程数据库
        /*fileInfo.setBtnstatus(ContantsUtils.PAUSE);
        Intent intent = new Intent(mContext,DownloadService.class);
        intent.putExtra("fileinfo",fileInfo);
        mContext.startService(intent);*/
        if (mBinder != null){
            mBinder.deleteDownload(fileInfo.getApkurl());
        }
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {  //2s之后删除数据库，因为暂停需要时间
            @Override
            public void run() {
                /*mDbThreadListener.deleteThread(fileInfo.getApkurl());
                for (FileInfo fileinfo: RemoteService.sFileInfoList)
                    Log.d(TAG, "delete: "+fileinfo.getFileName());*/
                boolean isThreadexsits = LitePalUtils.isThreadInfoExsits(fileInfo.getApkurl());
                if (isThreadexsits) {
                    DataSupport.deleteAll(ThreadInfo.class);
                }
                //第三步，修改任务队列
                for (int i = 0; i < RemoteService.sFileInfoList.size(); i++) {
                    FileInfo info = RemoteService.sFileInfoList.get(i);
                    if (fileInfo.getApkurl().equals(info.getApkurl())){
                        RemoteService.sFileInfoList.remove(i);  //删除数据
                    }
                }
                for (FileInfo fileinfo: RemoteService.sFileInfoList)
                    Log.d(TAG, "deletetask: "+fileinfo.getFileName());
                completedAndStartDownload(RemoteService.sFileInfoList);
            }
        },2000);




    }




    private String getFloatToString(Float value){
        DecimalFormat decimalFormat =
                new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        return  decimalFormat.format(value);
    }

    public void onDestory(){
        if (conn != null){
            mContext.unbindService(conn);
        }
    }

}
